package main

import (
	"context"
	"fmt"
	"geektime-cn/biz"
	"geektime-cn/http_service"
	"geektime-cn/http_service/logger"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"go.uber.org/zap"
)

func main() {
	log, err := logger.NewLogger()
	if err != nil {
		panic(fmt.Sprintf("init logger failed : %v", err))
	}

	zap.ReplaceGlobals(log)

	srv := http_service.NewHttpSrv(biz.Routers()...)

	done := make(chan os.Signal, 1)
	signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

	zap.S().Infof("version : %s", os.Getenv("VERSION"))

	go func() {
		if err := srv.ListenAndServe(":8080"); err != nil && err != http.ErrServerClosed {
			zap.S().Fatalf("listen: %s\n", err)
		}
	}()

	zap.S().Info("server started, listen at 8080")

	<-done

	zap.S().Info("server shutting down")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer func() {
		cancel()
	}()

	if err := srv.Shutdown(ctx); err != nil {
		zap.S().Fatalf("Server Shutdown Failed:%+v", err)
	}
	zap.S().Info("Server Exited Properly")
}
